﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using l1cs.server.model.Instance;
using l1cs.server.datatables;
using l1cs.server.model;
using System.Threading;

namespace l1cs.server.utils
{
    public class L1SpawnUtil
    {
        private static Logger _log = Logger.getLogger( typeof( L1SpawnUtil ).FullName );

        public static void spawn( L1PcInstance pc, int npcId, int randomRange, int timeMillisToDelete )
        {
            L1NpcInstance npc = NpcTable.getInstance().newNpcInstance( npcId );
            npc.setId( IdFactory.getInstance().nextId() );
            npc.setMap( pc.getMapId() );
            if ( randomRange == 0 )
            {
                npc.getLocation().set( pc.getLocation() );
                npc.getLocation().forward( pc.getHeading() );
            }
            else
            {
                int tryCount = 0;
                do
                {
                    tryCount++;
                    npc.setX( pc.getX() + (int)( ( new Random() ).Next( 1 ) * randomRange )
                            - (int)( ( new Random() ).Next( 1 ) * randomRange ) );
                    npc.setY( pc.getY() + (int)( ( new Random() ).Next( 1 ) * randomRange )
                            - (int)( ( new Random() ).Next( 1 ) * randomRange ) );
                    if ( npc.getMap().isInMap( npc.getLocation() )
                            && npc.getMap().isPassable( npc.getLocation() ) )
                    {
                        break;
                    }
                    Thread.Sleep( 1 );
                } while ( tryCount < 50 );

                if ( tryCount >= 50 )
                {
                    npc.getLocation().set( pc.getLocation() );
                    npc.getLocation().forward( pc.getHeading() );
                }
            }

            npc.setHomeX( npc.getX() );
            npc.setHomeY( npc.getY() );
            npc.setHeading( pc.getHeading() );

            L1World.getInstance().storeObject( npc );
            L1World.getInstance().addVisibleObject( npc );

            npc.turnOnOffLight();
            npc.startChat( L1NpcInstance.CHAT_TIMING_APPEARANCE ); // チャット開始
            if ( 0 < timeMillisToDelete )
            {
                L1NpcDeleteTimer timer = new L1NpcDeleteTimer( npc, timeMillisToDelete );
                timer.begin();
            }
        }
    }
}
